

function getPopup() {
  var views = chrome.extension.getViews({ type: 'popup' });
  if (views.length > 0) {
    return views[0]
  }
  return null;
}

/**
* 将url文件下载到本地
* @param fileUrl {String} 文件链接
* @param fileName {String} 文件名字
* @return void
*/
function downloadFile(fileUrl, fileName, options) {
  const xhr = new XMLHttpRequest();
  xhr.open('GET', fileUrl, true);
  //监听进度事件
  xhr.addEventListener(
    'progress',
    function (evt) {
      if (evt.lengthComputable) {
        let percentComplete = evt.loaded / evt.total;
        // percentage是当前下载进度，可根据自己的需求自行处理
        let percentage = percentComplete * 100;
        getPopup()?.uploadPercentage(Object.assign(options, {
          percentage: percentage.toFixed(2),
          type: xhr.getResponseHeader("Content-Type")
        }))
      }
    },
    false
  );
  xhr.responseType = 'blob';
  xhr.onload = () => {
    if (xhr.status === 200) {
      saveFile(xhr.response, fileName)
    }
  };
  xhr.send();
}
function saveFile(blob, fileName) {
  // ie的下载
  if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(blob, filename);
  } else {
    // 非ie的下载
    const link = document.createElement('a');
    const body = document.querySelector('body');

    link.href = window.URL.createObjectURL(blob);
    link.download = fileName;

    // fix Firefox
    link.style.display = 'none';
    body.appendChild(link);

    link.click();
    body.removeChild(link);

    window.URL.revokeObjectURL(link.href);
  }
}

